#include <stdio.h>
#include <string.h>
#include <assert.h>

#include "deflate.h"

#define DEFLATE_CHUNK 1024



#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
#  include <fcntl.h>
#  include <io.h>
#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
#else
#  define SET_BINARY_MODE(file)
#endif


/*********************************************************************************
	Deflate using zlib's gzip
**********************************************************************************/
int http_deflate(char* in, unsigned int* insize, char * out, unsigned int* outsize, int level)
{
	int ret;
	z_stream strm;

	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
 	strm.zalloc = Z_NULL;

	ret = deflateInit2(&strm, Z_BEST_COMPRESSION, Z_DEFLATED, 15+16, 8, Z_DEFAULT_STRATEGY);

	if(ret != Z_OK)
		return ret;

        strm.avail_in = *insize;
        strm.next_in = (Bytef*)in;

	strm.avail_out = *outsize;
	strm.next_out = (Bytef*)out;
	if((ret=deflate(&strm, Z_FINISH)) == Z_OK || ret==Z_STREAM_END){
		if(!strm.avail_out)
			ret=1;
		else{
			ret=0;
			*outsize = *outsize - strm.avail_out;
		}
	}
	else{
		return ret;
		//printf("zlib error %d\n", ret);
	}
	deflateEnd(&strm);
	return ret;
}

/*********************************************************************************
	Inflate using zlib's gzip
**********************************************************************************/
int http_inflate(char* in, unsigned int* insize, char * out, unsigned int* outsize, int level)
{
	int ret;
	z_stream strm;

	strm.zalloc = Z_NULL;
	strm.zfree = Z_NULL;
	strm.opaque = Z_NULL;
	strm.avail_in = 0;
	strm.next_in = Z_NULL;

	ret = inflateInit2(&strm, 15+16);

	if(ret != Z_OK)
		return ret;

        strm.avail_in = *insize;
        strm.next_in = (Bytef*)in;

	strm.avail_out = *outsize;
	strm.next_out = (Bytef*)out;
	if((ret=inflate(&strm, Z_FINISH)) == Z_OK || ret==Z_STREAM_END){
		if(!strm.avail_out)
			ret=1;
		else{
			*outsize = *outsize - strm.avail_out;
			ret=0;
		}
	}
	else{
		printf("zlib error %d\n", ret);
	}
	inflateEnd(&strm);
	return ret;
}
